<template>
  <div>
    <div class="bgBackground" :style="background" style="overflow-y: auto; overflow-x: paged-x;">
      <div style="height: 55px;width: 100%;min-width: 1000px;">
        <el-col :span="3" :offset="1">
          <div class="title_div" style="width: 200px">
            <h2 class="title_h2">
              <i class="el-icon-s-home"></i>
              弄个房租</h2>
          </div>
        </el-col>
        <el-col :span="1" :offset="1">
          <div>
            <el-button icon="el-icon-location" class="location_button" size="mini" @click="changeLocation()">
              {{ area.areaName }}
            </el-button>
          </div>
        </el-col>
        <el-col :span="9" :offset="4">
          <div>
            <ul class="header_ul">
              <li class="header_li" @click="toZHUFANG()">租房</li>
              <li class="header_li" @click="openChat()">联系管理员</li>
              <li class="header_li" @click="rental()">发布房源</li>
            </ul>
          </div>
        </el-col>
        <el-col :span="5">
          <div v-if="!user.userName" style="margin-top: 10px" @click="toLoginAndRegister()">
            <el-avatar :size="40" src="../../../../static/image/noLoginHeadImage.png"></el-avatar>
            <span class="login_register" style="color: white;font-size: 18px">登录/注册</span>
          </div>
          <div v-else style="margin-top: 10px">
            <el-avatar :size="40"
                       :src="user.headImage? 'http://192.168.123.150/'+user.headImage:'../../../../static/image/noLoginHeadImage.png'"></el-avatar>
            <el-popover
              placement="bottom"
              width="60px"
              style="padding: 0px;"
              trigger="hover">
              <ul style="list-style: none;padding: 0px 20px 0px 20px" class="my">
                <li style="margin-top: 5px" @click="showMessage()">消息</li>
                <li style="margin-top: 5px" @click="toPersonalCenter()">个人中心</li>
                <li style="margin-top: 5px" @click="logout()">退出</li>
              </ul>
              <!--              <el-button >click 激活</el-button>-->
              <span class="login_register" slot="reference"
                    style="color: white;font-size: 18px">{{ user.nickname }}</span>
            </el-popover>

          </div>
        </el-col>
      </div>
      <div style="height: 100px">
        <h1 style="margin-top: 90px;font-size: 60px;color: white;font-family: '宋体'">挑选适合你的家</h1>
      </div>
      <div style="height: 35px;font-size: 17px;width: 50%;margin-left: 0%">
        <ul>
          <li class="search_li" @click="button_text='开始找房';input_placeholder='请输入区域、商圈、小区名开始找房'">租房</li>
        </ul>
      </div>
      <div style="height: 120px;width: 40%;margin-left: 23%; ">
        <el-input v-model="text" :placeholder="input_placeholder">
          <el-button slot="append" @click="toRental()" style="background-color: #00ae66;color: white;border: none">开始找房
          </el-button>
        </el-input>
      </div>
      <div style="margin-top: 50px;width: 60%;margin-left: 20%">
        <el-carousel height="450px">
          <el-carousel-item v-for="item in imgList" :key="item.imgName">
            <div style="position:relative">
              <img :src="'../../../../static/image/'+item.imgName" style="margin-left: 0%" width="80%">
              <div style="position: absolute;right: 100px;
  color: #111512;
  font-size: 12px;
  top: 280px;
  width: 200px;
  height: 70px;
border:none;

">
                <el-card class="box-card" body-style="background-color: rgba(72,74,76,0.8);;color: white;">
                  <p>{{ '小区名:' + item.xqmc }}</p>
                  <p>{{ '位置：' + item.location }}</p>
                  <p>{{ '价格：' + item.price }}</p>
                </el-card>
              </div>
            </div>
          </el-carousel-item>
        </el-carousel>
      </div>
      <div style="height: 100px;float: left;margin-left: 10px">
        <el-link type="info" @click="toAdminPage()">管理员进入</el-link>
      </div>
      <!--    <router-link to="login">登录页面</router-link>-->
      <!--    <el-button @click="openChat()">打开聊天室</el-button>-->
      <ChatRoom v-if="chatOrList" ref='chatRoom' :to-user="toUser" :randomString="randomString"></ChatRoom>
<!--      我的消息-->
      <MyMessageList :user="user" :random-string="randomString1"></MyMessageList>
      <el-dialog
        :before-close="handleClose"
        :append-to-body="true"
        :title="title"
        :visible.sync="dialogVisible"
        width="750px">
        <div style="height: 350px">
          <el-form ref="rentalV0" :model="rentalV0" label-width="95px">
            <el-col :span="12">
              <el-form-item label="区域位置:" prop="qywzid" :rules="[
      { required: true, message: '请选择区域位置', trigger: 'blur' }]">
                <el-cascader
                  v-model="rentalV0.qywzid"
                  :options="options"
                  :props="props"></el-cascader>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="商圈名称:" prop="sqid">
                <el-select v-model="rentalV0.sqid">
                  <el-option v-for="item in businessData" :key="item.sqlsh" :label="item.sqmc"
                             :value="item.sqlsh"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">

              <el-form-item label="小区名称:" prop="xqid" :rules="[
      { required: true, message: '请选择小区', trigger: 'blur' }]">
                <el-select v-model="rentalV0.xqid">
                  <el-option v-for="item in communityData" :key="item.xqlsh" :label="item.xqmc"
                             :value="item.xqlsh"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="房屋类型:" prop="fwlx" :rules="[
      { required: true, message: '请选择房屋类型', trigger: 'blur' }]">
                <el-select v-model="rentalV0.fwlx">
                  <el-option v-for="item in dictFWLX" :key="item.dictValue" :label="item.dictLabel"
                             :value="item.dictValue"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="房间类型:" prop="fjlx" :rules="[
      { required: true, message: '请选择房间类型', trigger: 'blur' }]">
                <el-select v-model="rentalV0.fjlx">
                  <el-option v-for="item in dictFJLX" :key="item.dictValue" :label="item.dictLabel"
                             :value="item.dictValue"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="租房方式:" prop="zffs" :rules="[
      { required: true, message: '请选择租房方式', trigger: 'blur' }]">
                <el-select v-model="rentalV0.zffs">
                  <el-option v-for="item in dictZFFS" :key="item.dictValue" :label="item.dictLabel"
                             :value="item.dictValue"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="付款方式:" prop="fkfs" :rules="[
      { required: true, message: '请选择付款方式', trigger: 'blur' }]">
                <el-select v-model="rentalV0.fkfs">
                  <el-option v-for="item in dictFKFS" :key="item.dictValue" :label="item.dictLabel"
                             :value="item.dictValue"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="出租面积" prop="czmj"
                            :rules="[{ required: true, message: '请输入出租面积', trigger: 'blur' }, { type: 'number', message: '输入必须为数值！'}]">
                <el-input size="mini" style="width: 200px" v-model.number="rentalV0.czmj">
                  <span slot="suffix">m ²</span>
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="出租金额" prop="czje"
                            :rules="[{ required: true, message: '请输入出租金额', trigger: 'blur' }, { type: 'number', message: '输入必须为数值！'}]">
                <el-input size="mini" style="width: 200px" v-model.number="rentalV0.czje">
                  <span slot="suffix">元 / 月</span>
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="房屋门牌号" prop="fwmph"
                            :rules="[{ required: true, message: '请输入门牌号', trigger: 'blur' }]">
                <el-input size="mini" style="width: 200px" v-model="rentalV0.fwmph"></el-input>
              </el-form-item>
            </el-col>
          </el-form>
        </div>
        <div style="text-align: center">
          <el-upload
            class="upload-demo"
            ref="upload"
            action="127.0.0.1:8001/zmfpt-back/community/addCommunity"
            :on-preview="handlePreview"
            :on-remove="handleRemove"
            :on-change="fileChange"
            :file-list="fileList"
            :limit="7"
            :on-exceed="upMaxFile"
            list-type="picture"
            :auto-upload="false">
            <!--              this.$refs.upload.submit();-->
            <el-button slot="trigger" size="small" type="primary">选取房屋图片</el-button>
            <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且总共图片不能超过7张，不低于5张！</div>
          </el-upload>
          <el-image
            ref="myImg"
            v-show="false"
            src="http://192.168.123.150/images/business/20211230/1426f19d50b04bd88d3a7a991e91e2e6_IMG_9054.JPG"
            :preview-src-list="prewList">
          </el-image>
        </div>
        <span style="float: bottom; margin-bottom: 30px" slot="footer" class="dialog-footer">
                            <el-button @click="cancel()">取 消</el-button>
                          <el-button type="primary" @click="sureRental()">确 定</el-button>
                        </span>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import ChatRoom from '../components/ChatRoom'
import backImage from '../../static/image/home_beijing.png'
import MyMessageList from "../components/MyMessageList";

export default {
  name: "HomeMoudle",
  components: {
    ChatRoom,
    MyMessageList,
  },
  data() {
    return {
      toUser: {
        name: '管理员',
        id: '1',
        headImage: '../../../../static/image/noLoginHeadImage.png',
      },
      props: {
        value: 'areaId',
        label: 'areaName',
        children: 'children'
      },
      imgList: [
        {imgName: 'img1.png', price: '1200/月', location: '成都市青羊区北书院街2号'}, {
          imgName: 'img_1.png',
          price: '900/月'
        }, {
          imgName: 'img.png',
          price: '2000/月'
        }, {imgName: 'img_2.png', price: '1800/月'}],
      area: {
        areaName: '地区',
        areaId: ''
      },
      user: {
        headImage: '../../../../static/image/noLoginHeadImage.png',
        nickname: '',
        userId: ''
      },
      title: '发布房源',
      text: '',
      chatOrList:true,
      dialogVisible: false,
      rentalV0: {   //租房请求
        qywzid: '',
        sqid: '',
        xqid: '',
        czmj: '',
        fkfs: '',
        zffs: '',
        fwlx: '',
        fjlx: '',
        fwmph: '',
        czje: '',
      },
      options: [],
      businessData: [],
      communityData: [],
      dictFWLX: [],
      dictFJLX: [],
      dictFKFS: [],
      dictZFFS: [],
      prewList: [],   //预览
      fileList: [],   //照片
      addFileList: [], //新增
      isLoadDict: false,
      randomString: '',
      randomString1: '',
      messageList: [],
      input_placeholder: '请输入区域、商圈、小区名开始找房',
      background: {
        // 背景图片地址
        backgroundImage: `url(${backImage})`,
        width: '100%',
        height: '100%',
        position: 'fixed',

        // 背景图片是否重复
        backgroundRepeat: 'no-repeat',
        // 背景图片大小
        backgroundSize: '100% 100%',
        // 背景颜色
        backgroundColor: '#2b2b2b',
        // // 背景图片位置
        // backgroundPosition: 'center center',
      }
    }
  },
  mounted() {
    //获取之前存储在浏览器中的地址，并显示加载
    let area = JSON.parse(localStorage.getItem("area"))
    area && this.showArea(area)
    //通过token获取userInfo
    this.getUserInfo()
  },
  methods: {
    showChatMessage(item) {
      this.toUser = {
        id: item.showId,
        headImage: item.headImage,
        name: item.nickname
      }
      if (item.sendUserId === item.showId && item.isRead === '02') {
        let data = {
          userId: item.sendUserId,
          toUserId: this.user.userId,
          messageType: '09'
        }
        console.log(this.global.ws)
        console.log(this.global.ws.readyState)
        if (this.global.ws && this.global.ws.readyState == 1) {
          this.global.ws.send(JSON.stringify(data))
        }
      }
      this.randomString = Math.random().toString(36).slice(-6);
    },
    getMessageList() {
      this.$axios({
        url: '/getMessageList',
        method: "get",
        params: {
          userId: this.user.userId
        }
      }).then(res => {
        if (res.data.code === 200) {
          this.messageList = res.data.data
        }
      })
    },
    showMessage() {
      // this.getMessageList()
      this.randomString1 = Math.random().toString(36).slice(-6);
      console.log(111)
    },

    //跳转租房页面
    toRental() {
      this.$router.push({
        path: "/rentalList",
        query: {text: this.text}
      })
    },
    //确定提交租房申请
    sureRental() {
      if (this.addFileList.length < 5) {
        this.$message.error("请选择5张以上照片发布！")
        return false
      }
      this.$refs["rentalV0"].validate((valid) => {
        if (valid) {
          let from = new FormData()
          this.addFileList.forEach(item => {
            from.append("files", item.raw)
          })
          from.append("qywzid", this.rentalV0.qywzid.join(';'))
          from.append("sqid", this.rentalV0.sqid)
          from.append("xqid", this.rentalV0.xqid)
          from.append("czmj", this.rentalV0.czmj)
          from.append("fkfs", this.rentalV0.fkfs)
          from.append("zffs", this.rentalV0.zffs)
          from.append("fwlx", this.rentalV0.fwlx)
          from.append("fjlx", this.rentalV0.fjlx)
          from.append("fwmph", this.rentalV0.fwmph)
          from.append("czje", this.rentalV0.czje)
          from.append("fdid", this.$store.state.users.userId)
          this.$axios({
            url: '/rental/addRentalInfo',
            method: "post",
            data: from
          }).then(res => {
            if (res.data.code === 200) {
              this.$message.success("发布成功！")
              this.handleClose()
            } else {
              this.$message.error("发布失败！")
            }
          })
        } else {
          return false;
        }
      })
    },
    handleClose() {
      this.$refs['rentalV0'].resetFields()
      this.fileList = []
      this.dialogVisible = false
      this.addFileList = []
    },
    //获取区域树
    getAreaTree() {
      this.$axios({
        url: "/area/getAreaTree",
        get: "get",
      }).then(res => {
        this.options = res.data.data
      })
    },
    //获取商圈
    getBusiness(val) {
      this.$axios({
        url: '/business/getSqByQywzid',
        method: 'get',
        params: {
          qywzid: val
        }
      }).then(res => {
          this.businessData = res.data.data
        }
      )
    },
    //重置
    toRestFild(ref) {
      this.$nextTick(() => {
        this.$refs[ref].resetFields()
      })
    },
    //取消发布房源
    cancel() {
      this.toRestFild('rentalV0');
      this.fileList = []
      this.dialogVisible = false
      this.addFileList = []
    },
    //获取小区
    getCommunity() {
      this.$axios({
        url: '/getCommunity',
        method: 'get',
        params: {
          qywzid: this.rentalV0.qywzid.join(';'),
          sqid: this.rentalV0.sqid
        }
      }).then(res => {
          this.communityData = res.data.data
        }
      )
    },
    //点击发布房源
    rental() {
      let user = this.user
      if (!user.userId){
        this.$message.error("请先登录！")
        return ;
      }
      let roleList = JSON.parse(this.$store.state.users.roleList)
      if (roleList.indexOf("ROLE_MEMBER") >= 0) {
        this.getAreaTree()
        this.isLoadDict || this.toLoadDict()
        this.dialogVisible = true
      } else {
        this.$notify({
          title: '警告',
          dangerouslyUseHTMLString: true,
          message: '<span>请前往个人中心填写完个人信息后，完成后续操作！</span>',
          type: 'warning',
          offset: 100
        });
      }
    },
    upMaxFile(file, fileList) {
      this.$message.error("图片数量不能超过7张！")
    },
    fileChange(file, fileList) {
      let fileName = file.name
      console.log(file)
      let type = file.raw.type.split('/')[1].toUpperCase()
      if ( type === 'PNG' || type === 'JPG' || type === 'JPEG') {
        this.fileList.push(file)
        this.addFileList.push(file)
        this.prewList.push(file.url)
      } else {
        let index = fileList.indexOf(file)
        fileList.splice(index, 1)
        this.$message.error("注意上传图片为jpg、png格式！")
      }
    },
    handleRemove(file, fileList) {
      let index0 = this.fileList.indexOf(file)
      this.fileList.splice(index0, 1)
      let index = this.addFileList.indexOf(file)
      this.addFileList.splice(index, 1)
      let index2 = this.prewList.indexOf(file.url)
      this.prewList.splice(index2, 1)
    },
    handlePreview(file) {
      this.$refs.myImg.showViewer = true
    },
    toLoadDict() {
      this.$getDict('FWLX').then(res => {
        this.dictFWLX = res
      })
      this.$getDict('FJLX').then(res => {
        this.dictFJLX = res
      })
      this.$getDict('FKFS').then(res => {
        this.dictFKFS = res
      })
      this.$getDict('ZFFS').then(res => {
        this.dictZFFS = res
      })
      this.isLoadDict = true
    },
    toLoginAndRegister() {
      this.$router.push({path: "/login"})
    },
    openChat() {
      let user = this.user
      if (!user.userId){
        this.$message.error("请先登录！")
        return ;
      }
      this.toUser = {
        name: '管理员',
        id: 1,
        headImage: '/images/headImage/20220109/noLoginHeadImage.png',
      }
      this.randomString = Math.random().toString(36).slice(-6);
    },
    changeLocation() {
      //跳转到选择地区界面
      this.$router.push({path: "/selectArea"})
    },
    toZHUFANG() {
      this.$router.push({path: "/rentalList"})
    },
    showArea(area) {
      this.area = area
    },
    //通过token获取到用户信息
    getUserInfo() {
      this.$axios({
        method: "get",
        url: "/getUserInfo"
      }).then(res => {
        if (res.data.code === 200) {
          let user = res.data.data
          this.$store.commit("setUserId", user.id)
          this.$store.commit("setNickname", user.nickname)
          this.$store.commit("setName", user.username)
          this.$store.commit("setHeadImage", user.headImage)
          this.$store.commit("setRoleList", JSON.stringify(user.roleList))
          sessionStorage.setItem("roleList", user.roleList)
          this.user = {
            userId: user.id,
            userName: user.username,
            headImage: user.headImage,
            nickname: user.nickname
          }
        }

      })
    },
    logout() {
      this.$store.dispatch("logout");
      localStorage.removeItem("Authorization");
      this.user = {
        userId: '',
        userName: '',
        headImage: ''
      }
    },
    toAdminPage() {
      this.$router.push({name: "AdminModule"})
    },
    toPersonalCenter() {
      this.$router.push({name: "PersonalCenter"})
    },
    toTalking() {
      this.$axios({
        url: '/getUserByid',
        method: "get",
        params: {id: id}
      }).then(res => {
        if (res.data.code === 200) {
          console.log(res.data.data)
          let data = res.data.data
          this.toUser = {
            id: data.id,
            name: data.username,
            headImage: data.headImage
          }
        } else {
          this.$message.error("操作失败，请联系管理员！")
        }
      })
    },
  },
  watch: {
    'rentalV0.qywzid'(val) {
      this.rentalV0.sqid = ""
      this.rentalV0.sqmc = ""
      this.rentalV0.xqid = ""
      this.rentalV0.xqmc = ""
      if (val != '') {
        let data = val.join(';')
        this.getBusiness(data)
        this.getCommunity()
      }
    },
    'rentalV0.sqid'(val) {
      this.rentalV0.xqid = ""
      this.rentalV0.xqmc = ""
      if (val != '') {
        this.getCommunity();
      }
    },
  }
}
</script>

<style scoped>
body {
  margin: 20px;
  padding: 20px;
}

html,
body,
.bgBackground {
  /*width: 100%;*/
  height: 1000px
}

.title_h2 {
  font-family: "Arial", "Microsoft YaHei", "黑体", "宋体", sans-serif;
  color: white;
}

.location_button {
  height: 25px;
  margin-top: 25px;
  background-color: #2c3e50;
  color: white;
  border: none
}

.el-dialog__body {
  height: 600px;
  overflow: auto;
}

.header_li {
  display: inline;
  margin-left: 30px;
  color: white;
}

.header_ul .header_li:hover {
  cursor: pointer;
}

.my li:hover {
  background-color: #404040;
  cursor: pointer;
}

.login_register:hover {
  background-color: #404040;
  cursor: pointer;
}

.search_li {
  display: inline;
  color: white;
  margin-right: 50px;
}

.el-carousel__item h3 {
  color: #475669;
  font-size: 14px;
  opacity: 0.75;
  line-height: 150px;
  margin: 0;
}

.el-carousel__item:nth-child(n) {
  background-color: rgba(11, 15, 21, 0.5);

}

.carousel_p:nth-child(n) {
  position: absolute;
  right: 200px;
  color: #111512;
  font-size: 18px;
  top: 300px;
}

.title_div :hover {
  cursor: pointer;
}

/*.messageList li:hover {*/
/*  cursor: pointer;*/
/*}*/

</style>
